from flask import jsonify, request
from services.user_service import UserService
from services.auth_service import AuthService

class UserController:
    """用户控制器类 - 表现层"""
    
    def __init__(self):
        self.user_service = UserService()
        self.auth_service = AuthService()
    
    def get_profile(self):
        """获取用户个人信息"""
        try:
            # 从请求头获取token并验证
            token = request.headers.get('Authorization', '').replace('Bearer ', '')
            if not token:
                return jsonify({
                    'success': False,
                    'message': '缺少认证token'
                }), 401
            
            # 验证token并获取用户名
            payload = self.auth_service.verify_token(token)
            if not payload:
                return jsonify({
                    'success': False,
                    'message': 'token无效或已过期'
                }), 401
            
            username = payload.get('username')
            
            # 获取用户信息
            result = self.user_service.get_user_profile(username)
            
            return jsonify(result), result['status_code']
            
        except Exception as e:
            print(f"获取用户信息控制器错误: {e}")
            return jsonify({
                'success': False,
                'message': '获取用户信息失败，服务器错误'
            }), 500
    
    def update_profile(self):
        """更新用户个人信息"""
        try:
            # 从请求头获取token并验证
            token = request.headers.get('Authorization', '').replace('Bearer ', '')
            if not token:
                return jsonify({
                    'success': False,
                    'message': '缺少认证token'
                }), 401
            
            # 验证token并获取用户名
            payload = self.auth_service.verify_token(token)
            if not payload:
                return jsonify({
                    'success': False,
                    'message': 'token无效或已过期'
                }), 401
            
            username = payload.get('username')
            
            # 获取请求数据
            data = request.get_json()
            
            # 更新用户信息
            result = self.user_service.update_user_profile(username, data)
            
            return jsonify(result), result['status_code']
            
        except Exception as e:
            print(f"更新用户信息控制器错误: {e}")
            return jsonify({
                'success': False,
                'message': '更新用户信息失败，服务器错误'
            }), 500
    
    def change_password(self):
        """修改用户密码"""
        try:
            # 从请求头获取token并验证
            token = request.headers.get('Authorization', '').replace('Bearer ', '')
            if not token:
                return jsonify({
                    'success': False,
                    'message': '缺少认证token'
                }), 401
            
            # 验证token并获取用户名
            payload = self.auth_service.verify_token(token)
            if not payload:
                return jsonify({
                    'success': False,
                    'message': 'token无效或已过期'
                }), 401
            
            username = payload.get('username')
            
            # 获取请求数据
            data = request.get_json()
            
            # 验证必需字段
            if not data or 'currentPassword' not in data or 'newPassword' not in data:
                return jsonify({
                    'success': False,
                    'message': '请提供原密码和新密码'
                }), 400
            
            current_password = data.get('currentPassword')
            new_password = data.get('newPassword')
            
            # 修改密码
            result = self.user_service.change_password(username, current_password, new_password)
            
            return jsonify(result), result['status_code']
            
        except Exception as e:
            print(f"修改密码控制器错误: {e}")
            return jsonify({
                'success': False,
                'message': '修改密码失败，服务器错误'
            }), 500